package com.mirei.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mirei.entity.Hotel;
import com.mirei.entity.HotelDoc;
import com.mirei.mapper.HotelMapper;
import com.mirei.request.RequestParams;
import com.mirei.response.PageResult;
import com.mirei.service.IHotelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 1.全局搜索 searchV1
     * 2.加入条件搜索 关键词 城市 品牌 星级 价格区间
     * 3.传入位置 根据位置由近及远排序
     * 4.指定的酒店在搜索结果中排名置顶（广告功能）
     * 4.1给 HotelDoc 添加 Boolean 类型的 isAD 字段
     * 4.2将酒店 isAD 字段设置为 true AddHotelAD 文件
     * 4.3修改 search 方法，添加 function score 功能，为 isAD 值为 true 的酒店增加权重
     * <p>
     * 酒店数据自动补全：
     * 修改 hotel 索引库结构，设置自定义分词器
     * 修改索引库的 name，all 字段，使用自定义分词器
     * 索引库添加一个新字段 suggestion，类型为 completion 类型，使用自定义的分词器
     * 给 HotelDoc 类 添加 suggestion 字段，内容包含 brand、business
     * 重新导入数据到 hotel 库
     */
    @Override
    public PageResult search(RequestParams params) {
        Integer page = params.getPage();
        Integer size = params.getSize();
        String sortBy = params.getSortBy();
        List<String> sortList = new ArrayList<>();
        // 前端传来的坐标
        String location = params.getLocation();
        // 高亮查询 需要 request.source().highlighter(highlightBuilder);
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("name").requireFieldMatch(false);
        List<HighlightBuilder.Field> fields = highlightBuilder.fields();
        // 定位功能不好使 模拟定位
        // 加上定位功能 自定义 sort 根据评分排序失效
        location = "31.03463,121.61245";
        SearchRequest request = new SearchRequest("hotel");
        buildBoolQuery(params, request);
        request.source().from((page - 1) * size).size(params.getSize());
        request.source().highlighter(highlightBuilder);
        // 排序 排序功能不完善 只有一个sortBy 字段 应该还有一个 orderBy字段 提示升序还是降序
        // 默认排序 根据 score 排序 广告置顶
        // 非默认排序 根据价格/酒店评分排序 使用es的算分加分不好实现 mysql添加字段先根据置顶优先级字段排序再根据其他字段排序
        if (!StringUtils.isEmpty(sortBy) && !"default".equals(sortBy)) {
            request.source().sort(sortBy, SortOrder.ASC);
            sortList.add(sortBy);
            request.source().sort(SortBuilders.
                    geoDistanceSort("location", new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
            sortList.add("location");
        }
        try {
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            PageResult pageResult = buildPageResult(search, fields, sortList);
            return pageResult;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        //1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备 DSL
        buildBoolQuery(params, request);
        request.source().size(0);
        buildAggregation(request);
        //3.发出请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        //4.解析结果
        Map<String, List<String>> result = new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        List<String> brandList = getAggByName(aggregations, "brandAgg");
        result.put("brand", brandList);
        List<String> cityList = getAggByName(aggregations, "cityAgg");
        result.put("city", cityList);
        List<String> starList = getAggByName(aggregations, "starNameAgg");
        result.put("starName", starList);
        return result;
    }

    @Override
    public List<String> suggestion(String prefix) {
        List<String> response = new ArrayList<>();
        //1.准备 Request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders.completionSuggestion("titleSuggestion")
                        .prefix(prefix)
                        .skipDuplicates(true)
                        .size(10)));
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders.completionSuggestion("brandSuggestion")
                        .prefix(prefix)
                        .skipDuplicates(false)
                        .size(10)));
        //3.发起请求
        try {
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            //4.解析数据
            Suggest suggest = search.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                Map<String, Object> source = option.getHit().getSourceAsMap();
                String name = (String) source.get("name");
                response.add(name);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return response;
    }

    private static List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 获取 buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            brandList.add(keyAsString);
        }
        return brandList;
    }

    private static void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100));
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100));
        request.source().aggregation(AggregationBuilders
                .terms("starNameAgg")
                .field("starName")
                .size(100));
    }

    private static void buildBoolQuery(RequestParams params, SearchRequest request) {
        // 原始查询
        String key = params.getKey();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键字搜索
        if (StringUtils.isEmpty(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 条件过滤
        if (!StringUtils.isEmpty(params.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        if (!StringUtils.isEmpty(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (!StringUtils.isEmpty(params.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        // 价格区间
        if (!StringUtils.isEmpty(params.getMinPrice()) || !StringUtils.isEmpty(params.getMaxPrice())) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice()));
        }
        // 算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        // 其中的一个 function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                // 过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                // 算分函数
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                });
        request.source().query(functionScoreQuery);
    }

    public PageResult searchV1(RequestParams params) {
        String key = params.getKey();
        Integer page = params.getPage();
        Integer size = params.getSize();
        SearchRequest request = new SearchRequest("hotel");

        if (StringUtils.isEmpty(key)) {
            request.source().query(QueryBuilders.matchAllQuery());
        } else {
            request.source().query(QueryBuilders.matchQuery("all", key));
        }
        request.source().from((page - 1) * size).size(params.getSize());
//        HighlightBuilder highlightBuilder = new HighlightBuilder().field("name").requireFieldMatch(false);
//        List<HighlightBuilder.Field> fields = highlightBuilder.fields();
        // request.source() 相当于 DSL 中最外层的 {}
        try {
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            PageResult pageResult = buildPageResult(search, null, null);
            return pageResult;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private static PageResult buildPageResult(SearchResponse search, List<HighlightBuilder.Field> fields, List<String> sortList) {
        PageResult response = new PageResult();
        SearchHits searchHits = search.getHits();
        long total = searchHits.getTotalHits().value;
        log.info("共搜索到" + total + "条数据");
        SearchHit[] hits = searchHits.getHits();
        List<HotelDoc> hotelDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSONObject.parseObject(json, HotelDoc.class);
            Object[] sortValues = hit.getSortValues();
            // 默认排序 根据评分没有距离 需要完善
            // 非默认排序 位置在第二个排序
            if (sortList.contains("location")) {
                Object sortValue = sortValues[sortList.indexOf("location")];
                hotelDoc.setDistance(sortValue);
            }
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                for (HighlightBuilder.Field field : fields) {
                    HighlightField highlightField = highlightFields.get(field.name());
                    if (null != highlightField) {
                        String name = highlightField.getFragments()[0].string();
                        log.info(name);
                        hotelDoc.setName(name);
                    }
                }
            }
            hotelDocs.add(hotelDoc);
        }
        response.setHotels(hotelDocs);
        response.setTotal(total);
        return response;
    }
}
